﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using yq.IBase.Basis;

namespace yq.IBase.DBHelper.Tool
{
    internal class SQLiteTool : ITool
    {
        public Dictionary<string, string> GetTableList(DbHelper hp)
        {
            Dictionary<string, string> tableDic = new Dictionary<string, string>();

            //获取表
            const string sql = " SELECT * FROM sqlite_master WHERE type='table' ";
            var comm = hp.GetSqlStringCommond(sql);
            DataTable dt = hp.ExecuteDataTable(comm);

            //循环全部表
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string table = dt.Rows[i]["[Name]"].ToString();

                //获取列信息
                var com = hp.GetSqlStringCommond("PRAGMA table_info(" + table + ");");
                DataTable tableinfo = hp.ExecuteDataTable(com);

                //主键
                string key = "";

                for (int k = 0; k < tableinfo.Rows.Count; k++)
                {
                    if (dt.Rows[i]["pk"].ToString().Equals("1"))
                    {
                        key = dt.Rows[i]["name"].ToString();
                    }
                }

                if (key.Length==0)
                {
                    throw new Exception(table + "表没有主键");
                }

                tableDic.Add(table, key.ToString());
            }

            return tableDic;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public SelectSQL GetRowLock(SelectSQL sql)
        {
            return sql;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="top"></param>
        /// <returns></returns>
        public SelectSQL Top(SelectSQL sql, int top)
        {
            sql.End = sql.End +" limit 0," + top + " ";

            return sql;
        }
    }
}
